package com.pmsystem.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.pmsystem.service.FileService;

@Controller
public class FileController {

	@Autowired
	private FileService fileService;

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public Object uploadFile(HttpServletRequest request, MultipartFile file) throws IOException {
		//file.transferTo(new File(file.getOriginalFilename()));
		String fileName = file.getOriginalFilename();
		if (fileName == null || fileName.trim().equals("")) {
			return "error";
		}
		Date date = new Date();
		String today = new SimpleDateFormat("yyyy-MM-dd").format(date);
		// 上传文件摆放路径
		String url = request.getServletContext().getRealPath("/upload/" + today);
		//创建文件夹
		File file1 = new File(url);
		if (!file1.exists()) {
			file1.mkdirs();
		}
		FileCopyUtils.copy(file.getBytes(), new File(url + "/" + fileName));
		boolean flag = fileService.uploadFile(url, fileName, date);
		if(flag) {
			return "success";
		}		
		return "error";
	}
	
	@RequestMapping(value = "/download",method=RequestMethod.POST)
	@ResponseBody
	public Object download(HttpServletResponse response,@RequestParam Map<String,Object> map) throws IOException {
		String url = fileService.download(map);
		if (url == null || url.trim().equals("")) {
			return "error";
		}
		File file = new File(url);
		if (!file.exists()&&!file.isFile()) {
			return "error";
		}
		FileCopyUtils.copy(Files.newInputStream(file.toPath()), response.getOutputStream());
		return null;
	}

	@RequestMapping(value = "/findFile",method=RequestMethod.GET)
	@ResponseBody
	public Object findFile(@RequestParam Map<String,Object> map) {
		return fileService.findFile(map);
	}
	
	@RequestMapping(value = "/updateFile",method=RequestMethod.POST)
	@ResponseBody
	public Object updateFile(@RequestParam Map<String,Object> map) {
		boolean flag =  fileService.update(map);	
		if(flag) {
			return "success";
		}
		return "error";
	}
}
